# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 22:27:10 2025

@author: lenovo
"""

import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.dates as mdates
import cartopy.crs as ccrs
from cartopy.mpl.ticker import LongitudeFormatter,LatitudeFormatter
import cartopy.feature as cfeature
import shapely.geometry as sgeom
from datetime import datetime


class tydat_JMA:
    def __init__(self,path,skiprows=1,extent=[100,170,0,60]):  # default - dusurui
        self.df=pd.read_csv(path,skiprows=skiprows,engine='python',header=None,sep="\s+") 
        self.colors=['#000000','#00ffff','#0000ff', '#FF8C00','#FF0000','#FF00FF']
        lat= self.df[3].values*0.1
        lon=self.df[4].values*0.1
        self.lon,self.lat=self.cntrl_lonlat(lon,lat)
        self.extent=extent
        # 这里需要转成datetime对象
        self.time = [datetime.strptime("20"+str(t),'%Y%m%d%H') for t in self.df[0] ]
        self.pmin = self.df[5]
        self.umax = self.df[6]*0.514
        
    def cntrl_lonlat(self,lon,lat):
        lon = lon[(lon>=0) & (lon <=360)] #去异常   有e25次方
        lon=np.where(lon>180,180,lon)  #防止左右边界相连
        return lon,lat
    
    
def basemap(ax,ty,title=None):
    ax.add_feature(cfeature.COASTLINE,linewidth=0.5) #海岸线
    ax.add_feature(cfeature.BORDERS, linestyle=':')   #国界
    china_provinces = cfeature.NaturalEarthFeature(category='cultural',name='admin_1_states_provinces_lines', scale='10m', facecolor='none')
    ax.add_feature(china_provinces, edgecolor='black', linewidth=0.5) #省界
    ax.set(xlim=(ty.extent[0],ty.extent[1]))
    ax.set(ylim=(ty.extent[2],ty.extent[3]))    
    #这种设定方法适用于这样子给出范围。
    ax.set_xticks(np.linspace(ty.extent[0], ty.extent[1]+5, 5))
    ax.set_yticks(np.linspace(ty.extent[2], ty.extent[3]+5, 5))
    ax.xaxis.set_major_formatter(LongitudeFormatter(number_format='.1f'))
    ax.xaxis.set_minor_locator(plt.MultipleLocator(1))
    ax.yaxis.set_major_formatter(LatitudeFormatter(number_format='.1f'))
    ax.yaxis.set_minor_locator(plt.MultipleLocator(1))
    ax.tick_params(axis='both', labelsize=6, direction='out')
    ax.set_title(title)

def track(ax,ty,sep=1,color='Black'):
    lon= ty.lon
    lat= ty.lat
    ll2=np.arange(0,len(lon)-1,1)
    # 连线
    for i in ll2:
        pointA = lon[i],lat[i]
        pointB = lon[i+1],lat[i+1]
        ax.add_geometries([sgeom.LineString([pointA, pointB])], color=color,crs=ccrs.PlateCarree())  
        
        
pathobs = r"D:\met_data\ty_obs\mojie_obs.txt"
tyname = "mojie"
ty = tydat_JMA(pathobs)
fig,ax= plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()},dpi=300,figsize=(10,5))
basemap(ax,ty,title=tyname)  
track(ax,ty,color="lime")









